import type { TableColumnCtx } from 'element-plus'
import { uuid } from '@/utils'
import { getConsumptionSummaryStatistics } from '@/api/modules/consumption'

export type ColumnType = {
  label: string
  prop: string
} & Partial<Omit<TableColumnCtx<any>, 'label' | 'prop'>>
export function useEnergyConsumptionSummary() {
  const [loading, setLoading] = useState(false)
  const [columns, setColumns] = useShallowState<ColumnType[]>([])
  const [tableData, setTableData] = useState<any[]>([])

  async function getEnergyConsumptionSummaryData(
    params: {
      pointId: number
      startTime: string
      endTime: string
      all: boolean
      isIncludeSelf: boolean
    },
  ) {
    setLoading(true)
    try {
      const { data } = await getConsumptionSummaryStatistics(params)
      setColumns(data.thead);
      // uuid 作为 row-key
      (data.tbody || []).forEach((item: any) => {
        item.uuid = uuid()
      })
      setTableData((data.tbody || []).slice(0, 1))
      // setTableData([
      //   {
      //     uuid: uuid(),
      //     '1': '-',
      //     '2': '-',
      //     '3': '-',
      //     '4': '-',
      //     '5': '-',
      //     'pointId': 12,
      //     'pointName': '全厂',
      //     'pointNameFormat': '全厂',
      //     'hasLeaf': true,
      //     children: [
      //       {
      //         uuid: uuid(),
      //         '1': '-',
      //         '2': '-',
      //         '3': '-',
      //         '4': '-',
      //         '5': '-',
      //         'pointId': 14,
      //         'pointName': '一分厂',
      //         'pointNameFormat': ' 一分厂',
      //         'hasLeaf': true,
      //         children: []
      //       },
      //       {
      //         uuid: uuid(),
      //         '1': '-',
      //         '2': '-',
      //         '3': '-',
      //         '4': '-',
      //         '5': '-',
      //         'pointId': 16,
      //         'pointName': '二分厂',
      //         'pointNameFormat': ' 二分厂',
      //         'hasLeaf': true,
      //         children: []
      //       }
      //     ]
      //   },
      // ]);
    }
    catch (e) {
      console.warn(e)
    }
    finally {
      setLoading(false)
    }
  }

  async function loadEnergyConsumptionSummaryData(
    resolve: (data: any[]) => void,
    params: {
      pointId: number
      startTime: string
      endTime: string
      all: boolean
      isIncludeSelf: boolean
    },
  ) {
    try {
      const { data } = await getConsumptionSummaryStatistics(params);
      (data.tbody || []).forEach((item: any) => {
        item.uuid = uuid()
      })
      resolve(data.tbody || [])
    }
    catch (e) {
      console.warn(e)
      resolve([])
    }
  }

  return {
    loading,
    columns,
    tableData,
    getEnergyConsumptionSummaryData,
    loadEnergyConsumptionSummaryData,
  }
}
